package yxk.workflow;

import com.grapecity.documents.excel.Q;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 调动上级岗位人员成为流程审批人
 */
public class PositionSupPlugin implements IWorkflowPlugin {

    @Override
    public List<Long> calcUserIds(AgentExecution execution) {
        List<Long> userIdLists = new ArrayList<Long>();

        IWorkflowPlugin.super.calcUserIds(execution);
//        String pkId = execution.getBusinessKey();
        String billno = execution.getBusinessKey();
        QFilter qFilter = new QFilter("id", QCP.equals,billno);
        DynamicObject hdm_transferapply = BusinessDataServiceHelper.loadSingle(billno, "hdm_transferapply", "aposition.parent.number");
        String parenPosition = hdm_transferapply.getString("aposition.parent.number");
//        if(1==1){
//            userIdLists.add(1757581179273355264L);
//            userIdLists.add(1757863300013498368L);
//            return userIdLists;
//        }
        //获取上级职位
//        DataSet rows = QueryServiceHelper.queryDataSet(this.getClass().getName(), "hdm_transferapply", "aposition.parent.number as parenPosition", qFilter.toArray(), null);
//        String parenPosition = "";
//        for (Row row:rows){
//
//            parenPosition = row.getString("parenPosition");
//        }
        //根据上级职位获取在职职位人的id,根据任职经历去取
        Date totay = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dayStr = sdf.format(totay);
        qFilter = new QFilter("position.number", QCP.equals,parenPosition);
        qFilter = qFilter.and(new QFilter("enddate",QCP.large_equals,totay));
        qFilter = qFilter.and(new QFilter("datastatus",QCP.equals,"1"));
        DataSet empposorgrelRows = QueryServiceHelper.queryDataSet(this.getClass().getName(), "hrpi_empposorgrel", "person", qFilter.toArray(), null);
        List<Long> judgerIdList = new ArrayList<>();
        for (Row persons : empposorgrelRows) {
            judgerIdList.add(persons.getLong("person"));
        }
        if(judgerIdList.isEmpty()){
            return  null;
        }
        qFilter = new QFilter("person",QCP.in,judgerIdList);
        DataSet userIds = QueryServiceHelper.queryDataSet(this.getClass().getName(), "hrpi_personuserrel", "user", qFilter.toArray(), null);
        List<Long> userIdList = new ArrayList<Long>();
        for(Row row:userIds){
            userIdList.add(row.getLong("user"));
        }
        return userIdList;
    }
}
